//
//  HomeMainVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/5/26.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "HomeMainVC.h"
#import "BannerInfo.h"
#import "ActivityVC.h"


@interface HomeMainVC ()

@property(weak,nonatomic)IBOutlet UIScrollView *scrollView;

@property(weak,nonatomic)IBOutlet UIView *topView;
@property(weak,nonatomic)IBOutlet UILabel *topTitleLb;
@property(weak,nonatomic)IBOutlet UILabel *topBalanceLb;
@property(weak,nonatomic)IBOutlet UIButton *topBt;

@property(weak,nonatomic)IBOutlet UIView *leftView;
@property(weak,nonatomic)IBOutlet UIButton *leftTitleLb;
@property(weak,nonatomic)IBOutlet UILabel *leftProfitLb;
@property(weak,nonatomic)IBOutlet UIButton *leftBt;

@property(weak,nonatomic)IBOutlet UIView *rightView;
@property(weak,nonatomic)IBOutlet UIButton *rightTitleLb;
@property(weak,nonatomic)IBOutlet UILabel *rightCountLb;
@property(weak,nonatomic)IBOutlet UILabel *rightOnlineLb;
@property(weak,nonatomic)IBOutlet UIButton *rightBt;

@property(weak,nonatomic)IBOutlet UIView *bannerView;

@property(strong,nonatomic)NSMutableArray *bannerSource;


@end

@implementation HomeMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
    [self removeGesture];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateBalance];
    [self updateCard];
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    self.bannerSource = [[NSMutableArray alloc] init];
    float corner = 10;
    self.topView.layer.cornerRadius = corner;
    self.leftView.layer.cornerRadius = corner;
    self.rightView.layer.cornerRadius = corner;
    self.leftBt.layer.cornerRadius = globalRadius;
    self.rightBt.layer.cornerRadius = globalRadius;
    UIImage *img = createImageOfRC(globalRadius, self.leftTitleLb.bounds.size, colorWithString(@"#3d4358"));
    [self.leftTitleLb setBackgroundImage:img forState:UIControlStateNormal];
    [self.rightTitleLb setBackgroundImage:img forState:UIControlStateNormal];
    [[self.topBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"UserAccountVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [[self.leftBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil] instantiateViewControllerWithIdentifier:@"PointDetailVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [[self.rightBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"UserDeviceListVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"applicationWillEnterForeground" object:nil] subscribeNext:^(id x) {
        [self updateBalance];
        [self updateCard];
        [self requestData];
    }];
}


- (void)updateBalance {
    double point = 0.0;
    id data = getValueByKey(@"ss_point");
    if (data) {
        @try {
            point = [data doubleValue];
        } @catch (NSException *exception) {
            
        }
    }
    NSString *text = [[NSNumber numberWithDouble:point] stringValue];
    if (point == 0) {
        text = [[NSNumber numberWithDouble:point] stringValue];
    }
    self.topBalanceLb.attributedText = [self handleBigSmallText:text];
}

- (void)updateCard {
    NSString *address = getValueByKey(@"ss_wallet_address");
    if (!address) {
        self.topTitleLb.text = @"账户余额 (未绑定)";
    } else {
        self.topTitleLb.text = @"账户余额 (已绑定)";
    }
}

- (void)updateBanner {
    for (NSInteger i=self.bannerView.subviews.count-1; i>=0; i--) {
        [self.bannerView.subviews[i] removeFromSuperview];
    }
    float width = [UIScreen mainScreen].bounds.size.width-32;
    float height = width*300/656;
    float originY = 0;
    float margin = 12;
    for (int i=0; i<self.bannerSource.count; i++) {
        BannerInfo *banner = self.bannerSource[i];
        UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, originY, width, height)];
        containerView.backgroundColor = [UIColor clearColor];
        UIImageView *iv = [[UIImageView alloc] initWithFrame:containerView.bounds];
        [iv sd_setImageWithURL:[NSURL URLWithString:banner.imgUrl]];
        iv.layer.cornerRadius = 10;
        iv.layer.masksToBounds = YES;
        [containerView addSubview:iv];
        UIButton *bt = [[UIButton alloc] initWithFrame:containerView.bounds];
        [[bt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            if (banner.type && [banner.type isEqualToString:@"view"]) {
                NSString *url = banner.viewUrl;
                if (url && isNil(url) && url.length>0 && [url hasPrefix:@"http"]) {
                    ActivityVC *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ActivityVCID"];
                    [vc setTitle:banner.name url:banner.viewUrl];
                    [self.navigationController pushViewController:vc  animated:YES];
                }
                return;
            }
            if (banner.type && [banner.type isEqualToString:@"click"]) {
                @try {
                    NSString *sid = banner.clickEvent;
                    if ([sid isEqualToString:@"HomeMainVCID"]) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTab" object:@"0"];
                    } else if([sid isEqualToString:@"UserMainVCID"]){
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTab" object:@"1"];
                    } else {
                        UIViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:sid];
                        [self.navigationController pushViewController:vc  animated:YES];
                    }
                } @catch (NSException *exception) {
                    @try {
                        NSString *sid = banner.clickEvent;
                        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                        UIViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:sid];
                        [self.navigationController pushViewController:vc  animated:YES];
                    } @catch (NSException *exception) {
                        NSString *url = banner.viewUrl;
                        if (url && isNil(url) && url.length>0 && [url hasPrefix:@"http"]) {
                            ActivityVC *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ActivityVCID"];
                            [vc setTitle:banner.name url:banner.viewUrl];
                            [self.navigationController pushViewController:vc  animated:YES];
                        }
                    }
                }
            }
        }];
        [containerView addSubview:bt];
        [self.bannerView addSubview:containerView];
        originY+=height;
        originY+= margin;
    }
    CGRect rect = self.bannerView.frame;
    rect.size.height = originY;
    self.bannerView.frame = rect;
    self.scrollView.contentSize = CGSizeMake(0, rect.origin.y+originY);
}

- (void)requestData {
    //账户余额
    [[[HttpRequest shareInstance] signGet:w_point map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                id data = x[@"data"];
                if (data[@"point"]) {
                    saveValueByKey(data[@"point"], @"ss_point");
                    [self updateBalance];
                }
            } @catch (NSException *exception) {
                
            }
        }
    }];
    //钱包地址
    [[[HttpRequest shareInstance] signGet:s_wallet  map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                id data = x[@"data"];
                if (data) {
                    saveValueByKey(data, @"ss_wallet_address");
                } else {
                    removeValueByKey(@"ss_wallet_address");
                }
                [self updateCard];
            } @catch (NSException *exception) {
                
            }
        } else if ([x[@"code"] intValue] == 1005) {
            removeValueByKey(@"ss_wallet_address");
            [self updateCard];
        }
    } ];
    //设备昨日收益
    [[[HttpRequest shareInstance] signGet:w_yesterday_point map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                id data = x[@"data"];
                double profit = data ? [data doubleValue] : 0;
                NSNumber *number = [NSNumber numberWithDouble:profit];
                self.leftProfitLb.text = [number stringValue];
            } @catch (NSException *exception) {
                self.leftProfitLb.text = @"0";
            }
        } else {
            self.leftProfitLb.text = @"0";
        }
    } error:^(NSError *error) {
        self.leftProfitLb.text = @"0";
    }];
    // 设备列表
    [[[HttpRequest shareInstance] signGet:d_device_list map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                if (x[@"data"]) {
                    int totalCount = 0;
                    int count = 0;
                    for (NSDictionary *temp in x[@"data"]) {
                        NSError *error;
                        DeviceItem *deviceItem = [MTLJSONAdapter modelOfClass:[DeviceItem class] fromJSONDictionary:temp error:&error];
                        NSError *error2;
                        NSDictionary *temp2 = [temp objectForKey:@"deviceState"];
                        DeviceState *deviceState = nil;
                        NSArray *clients = nil;
                        NSArray *disk = nil;
                        RomUpgradePlan *romUpgradePlan = nil;
                        @try {
                            deviceState = [MTLJSONAdapter modelOfClass:[DeviceState class] fromJSONDictionary:temp2 error:&error2];
                        } @catch (NSException *exception) {
                            
                        }
                        NSError *error3;
                        NSError *error4;
                        if (isNil(temp2)) {
                            @try {
                                NSArray *temp3 = [temp2 objectForKey:@"clients"];
                                clients = [MTLJSONAdapter modelsOfClass:[Clinets class] fromJSONArray:temp3 error:&error3];
                                NSArray *temp4 = [temp2 objectForKey:@"disks"];
                                disk = [MTLJSONAdapter modelsOfClass:[Disks class] fromJSONArray:temp4 error:&error4];
                            } @catch (NSException *exception) {
                                
                            }
                        }
                        NSError *error5;
                        @try {
                            NSDictionary *temp5 = [temp objectForKey:@"romUpgradePlan"];
                            romUpgradePlan = [MTLJSONAdapter modelOfClass:[RomUpgradePlan class] fromJSONDictionary:temp5 error:&error5];
                        } @catch (NSException *exception) {
                            
                        }
                        if (!error) {
                            if (!error2 && deviceState) {
                                if (!error3 && clients) {
                                    deviceState.clients = clients;
                                }
                                if (!error4 && disk) {
                                    deviceState.disks = disk;
                                }
                                deviceItem.deviceState = deviceState;
                            }
                            if (!error5) {
                                deviceItem.romUpgradePlan = romUpgradePlan;
                            }
                            totalCount ++;
                            if ([deviceItem.deviceOnlineState boolValue]) {
                                count ++;
                            }
                        }
                    }
                    self.rightCountLb.text = [NSString stringWithFormat:@"设备数量：%d",totalCount];
                    self.rightOnlineLb.text = [NSString stringWithFormat:@"在线数量：%d",count];
                }
            } @catch (NSException *exception) {
                NSLog(@"error=%@",exception);
            }
        }
    }];
    // banner
    [[[HttpRequest shareInstance] signGet:Url_banner map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            NSError *error;
            NSArray *arr = [MTLJSONAdapter modelsOfClass:[BannerInfo class] fromJSONArray:x[@"data"] error:&error];
            if (!error) {
                [self.bannerSource removeAllObjects];
                [self.bannerSource addObjectsFromArray:arr];
                [self updateBanner];
            }
        } else {
            
        }
    } error:^(NSError *error) {
        
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}




@end
